<?php

namespace app\api\controller;

use app\common\controller\Api;
use addons\heycustoms\library\Heycustom\Heycustom;
use app\admin\model\HeyInfo;
use app\admin\model\Order;
use app\admin\model\OrderGoods;
use app\admin\model\HeyOrderRecord;
use fast\Random;
use fast\Http;
use think\Config;

/**
 * 拉取下属商场系统数据
 */
class HeyOrderCustoms extends Api
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    private $api_version = '1.0';
    private $country_list = false;

    private $errmsg = '';
    private $trans_count = 0;
    private $trans_time = 0;

    private $save_data = [];
    private $model;

    private $admin_id;

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     *
     * @return [type]
     */
    private function _init() {

    }

    public function test(){
        echo '<?xml version="1.0" encoding="utf-8"?>
        <root>
            <result_code>SUCCESS</result_code>
            <trade_no>2013111511001004390000105126</trade_no>
            <alipay_declare_no>2013112611001004680073956707</alipay_declare_no>
        </root>';
    }

    /**
     * 推送到海客云报关公共平台
     * @return [type] [description]
     */
    public function customs_push(){
        $order_id = $this->request->request('order_id');
        $return = $this->customs_push_one($order_id);
        if ($return) {
            $this->success($this->errmsg,$this->errmsg);
        }else{
            $this->error($this->errmsg,$this->errmsg);
        }
    }

    /**
     * 查询报关单状态
     * @return [type] [description]
     */
    public function customs_query(){
        $record_id = $_REQUEST['record_id'];
        $return = $this->customs_query_one($record_id);
        if ($return) {
            $this->success($this->errmsg,$this->errmsg);
        }else{
            $this->error($this->errmsg,$this->errmsg);
        }
    }

    /**
     * 根据订单号报关一条支付单
     * @param  [type] $order_id [description]
     * @return [type]           [description]
     */
    private function customs_push_one($order_id){
        // $admin_id = $this->request->request('admin_id');

        $order_info = Order::find($order_id);
        $this->admin_id = $order_info['admin_id'];
        $order_config = HeyInfo::getOrderConfig($this->admin_id);
        
        if (!$order_info) {
            $this->errmsg = '订单数据未查到';
            return false;
        }
        if (!$order_info['pay_sn']) {
            $this->errmsg = '支付单无数据';
            return false;
        }

        if (!$order_config || !isset($order_config['suzhou']) || !isset($order_config['suzhou']['ent_code'])) {
            $this->errmsg = '订单所属商户报关参数未设置';
            return false;
        }

        $order_config['suzhou']['ent_code'];
        $order_config['suzhou']['ent_name'];
        $order_config['suzhou']['ebp_code'];
        $order_config['suzhou']['ebp_name'];
        $order_config['suzhou']['customs'];
        $order_config['suzhou']['api_url'];
        $order_config['suzhou']['dxp_mode'];
        $order_config['suzhou']['dxp_id'];

        $heycustom = new Heycustom($order_config['suzhou']['api_url']);
        
        // 基础配置
        $base = [
            'copCode' => $order_config['suzhou']['ent_code'],
            'copName' => $order_config['suzhou']['ent_name'],
            'dxpMode' => $order_config['suzhou']['dxp_mode'],
            'dxpId' => $order_config['suzhou']['dxp_id'],
            // 'note' => $order_config['suzhou']['note'],
        ];

        if (!($heycustom->setBaseTransfer($base))) {
            $this->errmsg = $heycustom->errmsg;
            return false; 
        }

        // 订单信息
        $order = [
            'guid'              => $order_info['guid'],                     // 企业系统生成36位唯一序号（英文字母大写）。
            'appType'           => '1',                                     // 企业报送类型。1-新增 2-变更 3-删除。默认为1。
            'appTime'           => date('Ymdhis',time()),                   // 企业报送时间。格式:YYYYMMDDhhmmss。
            'appStatus'         => '2',                                     // 业务状态:1-暂存,2-申报,默认为2。
            'orderType'         => 'I',                                     // 电子订单类型：I进口
            'orderNo'           => $order_info['order_sn'],                 // 交易平台的订单编号，同一交易平台的订单编号应唯一。订单编号长度不能超过60位。
            'ebpCode'           => $order_config['suzhou']['ebp_code'],     // 电商平台的海关注册登记编号；电商平台未在海关注册登记，由电商企业发送订单的，以中国电子口岸发布的电商平台标识编号为准。
            'ebpName'           => $order_config['suzhou']['ebp_name'],     // 电商平台的海关注册登记名称；电商平台未在海关注册登记，由电商企业发送订单的，以中国电子口岸发布的电商平台名称为准。
            'ebcCode'           => $order_config['suzhou']['ent_code'],     // 电商企业的海关注册登记编号。
            'ebcName'           => $order_config['suzhou']['ent_name'],     // 电商企业的海关注册登记名称。
            'goodsValue'        => $order_info['goods_fee'],                // 商品实际成交价，含非现金抵扣金额。
            'freight'           => $order_info['ship_fee'],                 // 不包含在商品价格中的运杂费，无则填写"0"。
            'discount'          => $order_info['discount_fee'],             // 使用积分、虚拟货币、代金券等非现金支付金额，无则填写"0"。
            'taxTotal'          => $order_info['goods_tax'],                // 企业预先代扣的税款金额，无则填写“0”
            'acturalPaid'       => $order_info['order_fee'],                // 商品价格+运杂费+代扣税款-非现金抵扣金额，与支付凭证的支付金额一致。
            'currency'          => $order_info['currency'] == 'CNY'?'142':'142',                          // 限定为人民币，填写“142”。
            'buyerRegNo'        => $order_info['buyer_id'],                 // 订购人的交易平台注册号。
            'buyerName'         => $order_info['buyer_name'],               // 订购人的真实姓名。
            'buyerIdType'       => $order_info['buyer_id_type'],            // 1-身份证,2-其它。限定为身份证，填写“1”。
            'buyerIdNumber'     => $order_info['buyer_id_no'],              // 订购人的身份证件号码。
            'buyerTelephone'    => $order_info['buyer_mobile'],             // 海关监管对象的电话，要求实际联系电话
            'payCode'           => $order_info['pay_scope'] == 'alipay'?'312226T001':'',                  // 支付企业的海关注册登记编号。
            'payName'           => $order_info['pay_scope'] == 'alipay'?'支付宝(中国)网络技术有限公司':'',   // 支付企业在海关注册登记的企业名称。
            'payTransactionId'  => $order_info['pay_sn'],         // 支付企业唯一的支付流水号。
            'batchNumbers'      => 'OMS'.date('Ymd',strtotime($order_info['create_time'])),               // 商品批次号。
            'consignee'         => $order_info['receive_name'],             // 收货人姓名，必须与电子运单的收货人姓名一致。
            'consigneeTelephone'=> $order_info['receive_mobile'],           // 收货人联系电话，必须与电子运单的收货人电话一致。
            'consigneeAddress'  => $order_info['ship_address'],             // 收货地址，必须与电子运单的收货地址一致。
            'consigneeDistrict' => $order_info['ship_zipcode'],         // 参照国家统计局公布的国家行政区划标准填制。
            'note'              => $order_info['order_note'],
        ];
        
        if (!($heycustom->setOrderHead($order))) {
            $this->errmsg = $heycustom->errmsg;
            return false; 
        }

        // 商品数据
        $order_list = [];
        $order_goods = OrderGoods::with('goods')->where('order_sn',$order_info['order_sn'])->select();
        if (!empty($order_goods)) foreach ($order_goods as $_key => $_row) {

            /*验证商品是否已在平台备案*/
            // if ($_row['goods']['record_status'] != 'success') {
            //     $this->errmsg = '商品 '.$_row['goods']['goods_name'].' 未备案';
            //     return false;
            // }
            
            $order_list[] = [
                'gnum'          => $_key+1,
                'itemNo'        => $_row['goods']['goods_sn'],
                'itemName'      => $_row['goods']['goods_name'],
                'gmodel'        => $_row['goods']['goods_name'].$_row['goods']['brand_name'].$_row['goods']['goods_spec'],
                'itemDescribe'  => $_row['goods']['goods_desc'],
                'barCode'       => $_row['goods']['bar_code'],
                'unit'          => $_row['goods']['unit_code'],
                'qty'           => $_row['buy_number'],
                'price'         => $_row['goods']['goods_price'],
                'totalPrice'    => $_row['total_price'],
                'currency'      => $order_info['currency'] == 'CNY'?'142':'142',
                'country'       => $_row['goods']['country_code'],
                'note'          => $_row['buy_note'],
            ];
        }

        if (!($heycustom->setOrderList($order_list))) {
            $this->errmsg = $heycustom->errmsg;
            return false; 
        }

        /*准备数据*/
        $xml_data = $heycustom->setData();
        $this->model_data($xml_data, $order_info);

        $extra = [
            // 'request_param' => $xml_data,    // 请求参数
        ];

        $custom_res = $heycustom->query($xml_data);

        if ($custom_res && isset($custom_res['result_code'])) {  // 推送成功
            $custom_respose = $custom_res;
            if ($custom_respose['result_code'] == 'SUCCESS') {
                // 业务正常 //
                $this->set_response('submitted', 'PUSH_SUCCESS', '已推送到网关', $extra);

            }elseif ($custom_respose['result_code'] == 'FAIL') {
                // 业务出错 //
                $custom_respose['detail_error_code'];   // 错误码
                $custom_respose['detail_error_des'];    // 错误描述
                $this->set_response('failure', $custom_respose['detail_error_code'], $custom_respose['detail_error_des'], $extra);
            }

        }elseif ($custom_res && isset($custom_res['result_code']) && $custom_res['result_code'] == 'F') {
            // 请求失败或者接入数据错误 //
            $custom_res['error'];    // 错误代码
            $this->set_response('except', $custom_res['error'], '支付宝推送错误:'.$custom_res['error'], $extra);
                
        }else{
            // 系统错误 //
            $this->errmsg = $heycustom->errmsg;
            $this->set_response('except', 'API_EXCEPT', '接口异常：'.$this->errmsg?$this->errmsg:'返回结果异常', $extra);
        }
        /*保存数据*/
        if ($flag = $this->model_save($xml_data, $order_info)) {
            return true; 
        }else{
            $this->errmsg = '数据保存异常';
            return false; 
        }
    }

    /**
     * 根据订单号报关一条支付单
     * @param  [type] $order_id [description]
     * @return [type]           [description]
     */
    private function customs_query_one($record_id){
        // $admin_id = $this->request->request('admin_id');

        $record_info = HeyPayRecord::find($record_id);
        $admin_id = $record_info['admin_id'];
        $order_config = HeyInfo::getPayConfig($admin_id);
        
        if (!$record_info) {
            $this->errmsg = '订单数据未查到';
            return false;
        }

        if ($record_info['pay_scope'] == 'alipay') {

            if (!$record_info['out_request_no']) {
                $this->errmsg = '支付单无数据';
                return false;
            }

            if ($order_config && $order_config['alipay']) {

                if (!$order_config['alipay']['alipay_ent_code'] || !$order_config['alipay']['alipay_ent_code']) {
                    $this->errmsg = '订单所属商户报关参数未设置';
                    return false;
                }

                $param = [
                    'out_request_no' => $record_info['out_request_no'],
                ];
                // var_dump($param);exit;
                /*支付宝报关*/
                $alipayGateway = new AlipayGateway($order_config['alipay']);
                $alipay_res = $alipayGateway->query($param);

                /*准备数据*/
                $this->alipay_model_data('query' ,$param, $record_info);

                if ($alipay_res && $alipay_res['is_success'] == 'T') {
                    $alipay_respose = $alipay_res['response']['alipay'];

                    if ($alipay_respose['result_code'] == 'SUCCESS') {
                        if (!isset($alipay_respose['records'])) {
                            $this->errmsg = '未查询到此单';
                            return false;
                        }
                        // 只拿第一条
                        $customs_declare = isset($alipay_respose['records']['customs_declare'][0])?$alipay_respose['records']['customs_declare'][0]:$alipay_respose['records']['customs_declare'];

                        // 业务正常 //
                        $customs_declare['trade_no'];   // 支付单据号
                        $customs_declare['customs_place'];   // 海关编号。
                        $customs_declare['merchant_customs_code'];   // 商户在海关备案的编号
                        $customs_declare['merchant_customs_name'];   // 商户海关备案的名称
                        $extra = [
                            'out_request_no' => $customs_declare['out_request_no'],   // 商户端报关请求号
                            'customs_status' => $customs_declare['status'],   // 报关单当前的状态
                            'customs_time' => $customs_declare['last_modified_time'],   // 状态最后更新时间
                            'customs_memo' => implode('|', $customs_declare['memo']),   // 返回备注
                            'customs_code' => $customs_declare['customs_code'],    // 海关返回回执 2：支付单新增申报成功 120：海关入库 小于0的数字：表示处理异常回执
                            'customs_info' => $customs_declare['customs_info'],   // 海关结果描述信息
                            'customs_return_time' => $customs_declare['customs_return_time'],   // 海关返回回执的时间
                        ];

                        if ($customs_declare['status'] == 'ws') {
                            $this->set_response('processing', 'PROCESSING_WS', '等待发送海关', $extra);
                        }elseif ($customs_declare['status'] == 'sending') {
                            $this->set_response('processing', 'PROCESSING_SENDING', '已提交发送海关', $extra);
                        }elseif ($customs_declare['status'] == 'succ') {
                            $this->set_response('success', 'SUCCESS', $customs_declare['customs_info'], $extra);
                            // if ($customs_declare['customs_code'] == '2') {
                            //     $this->set_response('success', 'SUCCESS_ADDED', $customs_declare['customs_info'], $extra);
                            // }elseif ($customs_declare['customs_code'] == '120') {
                            //     $this->set_response('success', 'SUCCESS_FILLED', $customs_declare['customs_info'], $extra);
                            // }elseif ($customs_declare['customs_code'] < 0) {
                            //     $this->set_response('failure', 'CUSTOM_FAILURE', $customs_declare['customs_info'], $extra);
                            // }else{
                            //     $this->set_response('except', 'CUSTOM_EXCEPT', $customs_declare['customs_info'], $extra);
                            // }
                        }

                    }elseif ($alipay_respose['result_code'] == 'FAIL') {
                        // 业务出错 //
                        $alipay_respose['detail_error_code'];   // 错误码
                        $alipay_respose['detail_error_des'];    // 错误描述
                        $this->set_response('failure', $alipay_respose['detail_error_code'], $alipay_respose['detail_error_des']);
                    }

                    /*用户身份信息申报*/
                    if (isset($alipay_respose['identity_check']) && $alipay_respose['identity_check'] == 'T') {
                        // 身份校验匹配成功 //
                        $this->set_buyer_status(true);
                    }elseif (isset($alipay_respose['identity_check']) && $alipay_respose['identity_check'] == 'F') {
                        // 身份校验不匹配 //
                        $this->set_buyer_status(false);
                    }

                }elseif ($alipay_res && $alipay_res['is_success'] == 'F') {
                    // 请求失败或者接入数据错误 //
                    $alipay_res['error'];    // 错误代码
                    $this->set_response('except', $alipay_res['error'], '支付宝报关错误:'.$alipay_res['error']);
                        
                }else{
                    // 系统错误 //
                    $this->set_response('except', 'API_EXCEPT', '支付宝接口异常');
                }
                /*保存数据*/
                if ($flag = $this->model_save($param, $record_info)) {
                    return true; 
                }else{
                    $this->errmsg = '数据保存异常';
                    return false; 
                }

            }else{
                $this->errmsg = '支付宝参数配置不正确';
                return false; 
            }
        }elseif ($record_info['scope'] == 'wechat') {
            $this->errmsg = '微信支付报关未接入';
            return false;    
        }else{
            $this->errmsg = '订单支付方式无法进行报关';
            return false;
        }
    }

    private function model_data($request_param, $data_info){
        $data_arr = [
            'admin_id' => $data_info['admin_id'],
            'order_id' => $data_info['order_id'],
            'order_sn' => $data_info['order_sn'],
            'request_param' => json_encode($request_param, JSON_UNESCAPED_UNICODE),
            'record_time' => time(),
            // 'buyer_status' => $data_info['buyer_status'],
            // 'response_code' => $data_info['response_code'],
            // 'response_msg' => $data_info['response_msg'],
            // 'record_status' => $data_info['record_status'],
            // 'verify_depart' => $data_info['verify_depart'],
            // 'depart_trade_no' => $data_info['depart_trade_no'],
        ];
        return $this->save_data = $data_arr;
    }

    /**
     * 保存数据
     * @return [type] [description]
     */
    private function model_save(){
        $model = new HeyOrderRecord();
        // var_dump($this->save_data);exit;
        if (isset($this->save_data['id'])) {
            $flag = $model->update($this->save_data);
        }else{
            $flag = $model->save($this->save_data);
        }

        // 将信息同步到订单
        $order_info = Order::where(['admin_id'=>$this->admin_id,'order_sn'=>$this->save_data['order_sn']])->find();

        if ($order_info['order_status'] != 'success') {
            $order_data = [];
            if (isset($this->save_data['record_status'])) {
                $order_data['order_status'] = $this->save_data['record_status'];
            }
            if (!empty($order_data)) {
                $seflag = Order::where(['id'=>$order_info['id']])->update($order_data);
            }
        }

        return $flag;
    }

    /**
     * 设置报关推送返回值
     * @param string $record_status   状态
     * @param string $response_code   返回值
     * @param string $response_msg    返回值描述
     * @param string $verify_depart   核验机构
     * @param string $depart_trade_no 核验机构流水号
     */
    private function set_response($record_status = 'success', $response_code = '', $response_msg = '', $extra = array()) {
        $this->errmsg = $response_msg;

        $this->save_data = array_merge($this->save_data, $extra);

        $this->save_data['response_code'] = $response_code;
        $this->save_data['response_msg'] = $response_msg;

        if (strtolower($record_status) == 'success') {
            $this->save_data['record_status'] = 'success';

        }elseif (strtolower($record_status) == 'failure') {
            $this->save_data['record_status'] = 'failure';

        }elseif (strtolower($record_status) == 'submitted') {
            $this->save_data['record_status'] = 'submitted';

        }elseif (strtolower($record_status) == 'processing') {
            $this->save_data['record_status'] = 'processing';
                
        }else{
            $this->save_data['record_status'] = 'except';

        }
    }

}
